<template>
  <!-- 详情 -->
  <el-dialog
    v-el-drag-dialog
    title="安检计划"
    :visible.sync="visible"
    width="70%"
    min-width="1024px"
    append-to-body
    @close="reset"
  >
    <div class="item">
      <!-- <div class="title">
        <span class="title-icon" />
        <span class="title-text">安检计划信息</span>
      </div> -->
      <el-descriptions size="medium">
        <el-descriptions-item label="编号">{{ temp.planCode }}</el-descriptions-item>
        <el-descriptions-item label="计划名称">{{ temp.planName }}</el-descriptions-item>
        <el-descriptions-item label="客户类型">{{ csmTypes() }}</el-descriptions-item>
      </el-descriptions>
      <el-descriptions size="medium">
        <el-descriptions-item label="安检范围">{{ temp.scopeNames }}</el-descriptions-item>
      </el-descriptions>
      <el-descriptions size="medium">
        <el-descriptions-item label="审核人">{{ temp.auditor }}</el-descriptions-item>
        <el-descriptions-item label="审核日期">{{ temp.auditDt && parseTime(temp.auditDt, '{y}-{m}-{d} {h}:{i}:{s}') }}</el-descriptions-item>
      </el-descriptions>
      <el-descriptions size="medium">
        <el-descriptions-item label="备注">{{ temp.remark }}</el-descriptions-item>
      </el-descriptions>
    </div>
    <div class="item">
      <!-- <div class="title">
        <span class="title-icon" />
        <span class="title-text">其他信息</span>
      </div>
    </div> -->
      <div class="item">
        <el-tabs v-model="activeName" style="min-height: 200px;" type="card" @tab-click="tabsClick">
          <el-tab-pane lazy label="安检人员明细" name="personnelInfo">
            <lb-table
              ref="lbTable"
              border
              highlight-current-row
              element-loading-text="加载中"
              :column="tableData.column"
              :data="tableData.data"
              pagination
              show-summary
              :immediate-fetch="false"
              :total="tableData.total"
              custom-column
              @fetch="fetchData"
            />
          </el-tab-pane>
          <el-tab-pane lazy label="安检客户明细" name="clientInfo">
            <el-table-form ref="form">

              <el-form-item class="merge-item">
                <el-select v-model="qType" style="width: 180px; margin-right: 2px;">
                  <el-option label="客户电话" value="csmPhone" />
                  <el-option label="客户名称" value="csmName" />
                  <el-option label="客户编号" value="csmCode" />
                  <el-option label="客户地址" value="csmAddress" />
                  <el-option label="安检单号" value="childPlanCode" />
                </el-select>
                <el-input v-model="param" placeholder="请输入" clearable />
              </el-form-item>

              <el-form-item label="所属机构:">
                <el-tree-select
                  v-model="query.orgSNNo"
                  :clearable="false"
                  class="tree-select"
                  :popover-width="360"
                  :select-params="{
                    clearable: false,
                    placeholder: '请选择责任机构',
                  }"
                  :tree-params=" {
                    'default-expand-all': true,
                    'expand-on-click-node': false,
                    'highlight-current': true,
                    props:{
                      value:'orgSNNo',
                      label: 'orgName',
                      disabled: 'disabled',
                    },
                    data: treeData
                  }"
                  @node-click="selectTreeChange"
                />
              </el-form-item>

              <el-form-item label="安检人:" class="merge-item">
                <el-select v-model="query.checkUserId" placeholder="请选择">
                  <el-option v-for="(v,i) in personMap" :key="i" :label="v.userName" :value="v.userId" />
                </el-select>
              </el-form-item>

              <el-form-item class="merge-item" label="状态:">
                <el-select v-model="query.isChecked" style="width: 180px; margin-right: 2px;">
                  <el-option label="未安检" :value="1" />
                  <el-option label="安检未审核" :value="2" />
                  <el-option label="已安检" :value="3" />
                </el-select>
              </el-form-item>

              <template v-slot:btns>
                <el-button type="primary" icon="el-icon-search" @click="search">查询</el-button>
                <el-button type="primary" @click="assignPlan">转派</el-button>
              </template>
            </el-table-form>
            <lb-table
              ref="lbTablePer"
              v-loading="$loadingPlugin.fetchDataPer"
              v-el-height-adaptive-table="{bottomOffset:10}"
              border
              highlight-current-row
              element-loading-text="加载中"
              header-row-class-name="table-row-name"
              :column="column"
              :data="tableData1.data"
              pagination
              :immediate-fetch="false"
              :total="tableData1.total"
              custom-column
              @fetch="fetchDataPer"
            />
          </el-tab-pane>
        </el-tabs>
      </div>
    </div>
    <div slot="footer" class="dialog-footer">
      <el-button @click="reset">关闭</el-button>
    </div>
    <households-list ref="households" />
    <redeploy ref="redeploy" @redUpDataTable="redUpDataTable" />
  </el-dialog>
</template>

<script>
  import { gasCheckPlanPersonList, gasCheckPlanClientMember, gasCheckPlanClientList } from '@/api'
  import { parseTime, formatColumnMap } from '@/utils'
  import HouseholdsList from './HouseholdsList'
  import Redeploy from './Redeploy'

  export default {
    name: 'plan-info',
    components: {
      HouseholdsList,
      Redeploy
    },
    props: {
      csmTypeMap: {
        type: Array,
        required: true
      },
      treeData: {
        type: Array,
        required: true
      }
    },
    data() {
      return {
        parseTime,
        visible: false,
        temp: {},
        activeName: 'personnelInfo',
        date: [],
        personList: [],
        tableData: { // 安检人员明细
          total: 0,
          data: [],
          column: [
            {
              prop: 'operator',
              label: '安检人员'
            },
            {
              prop: 'checkedCount',
              label: '已安检户数'
            },
            {
              prop: 'waitAuditCount',
              label: '安检未审核户数'
            },
            {
              prop: 'count',
              label: '未安检户数',
              render: (h, { row }) => {
                var unCheckCount = Number(row.totalCount) - Number(row.checkedCount) - Number(row.waitAuditCount)
                return (
                  <div>
                    <el-link size='mini' onClick={() => this.notHouseholds(row, 1)}>{unCheckCount === 0 ? 0 : unCheckCount}</el-link>
                  </div>
                )
              }
            },
            {
              prop: 'totalCount',
              label: '安检总户数',
              render: (h, { row }) => {
                return (
                  <div>
                    <el-link size='mini' onClick={() => this.notHouseholds(row, -1)}>{row.totalCount}</el-link>
                  </div>
                )
              }
            },
            {
              prop: 'warnCount',
              label: '隐患户数'
            }
          ]
        },
        personMap: [],
        qType: 'csmPhone',
        param: '',
        headerCheckbox: false,
        query: {
          orgSNNo: '',
          checkUserId: '',
          isChecked: ''
        },
        // 安检客户明细
        tableData1: { // 安检人员明细
          total: 0,
          data: []
        }
      }
    },
    computed: {
      csmTypes() {
        return function() {
          return formatColumnMap(this.csmTypeMap, 'value', this.temp.csmTypes, 'desc')
        }
      },
      column: function() {
        return [
          {
            prop: 'isCheckbox',
            align: 'center',
            width: 60,
            renderHeader: (h, { row }) => {
              return h('div', [
                h('el-checkbox', {
                  props: {
                    value: this.headerCheckbox
                  },
                  on: {
                    change: this.changeBox
                  }
                })
              ])
            },
            render: (h, { row, $index }) => {
              return h('el-checkbox', {
                props: {
                  value: row.isCheckbox
                },
                on: {
                  change: () => { this.onChangeBox($index) }
                }
              })
            }
          },
          {
            prop: 'csmCode',
            label: '客户编号'
          },
          {
            prop: 'csmName',
            label: '客户名称'
          },
          {
            prop: 'csmPhone',
            label: '电话'
          },
          {
            prop: 'orgName',
            label: '所属机构'
          },
          {
            prop: 'csmAddress',
            label: '地址'
          },
          {
            prop: 'checkUser',
            label: '安检人'
          },
          {
            prop: 'warnLevel',
            label: '隐患等级',
            render: (h, { row }) => {
              var obj = {
                0: '无隐患',
                1: '一般隐患',
                2: '严重隐患',
                3: '隐患',
                4: 'level4',
                5: 'level5'
              }
              return <span>{obj[row.warnLevel]}</span>
            }
          },
          {
            prop: 'checkStatus',
            label: '状态',
            render: (h, { row }) => {
              var obj = {
                1: '安检未审核',
                2: '已安检'
              }
              return <span>{obj[row.checkStatus] === undefined ? '未安检' : obj[row.checkStatus] }</span>
            }
          }
        ]
      }
    },
    created() {},
    methods: {
      async open(temp) {
        this.temp = temp
        await Promise.all([this.personLsit()])
        return new Promise(resolve => {
          this.resolve = resolve
          this.visible = true
          this.$nextTick(() => {
            this.$refs.lbTable.fetch({ currentPage: 1 })
          })
        })
      },
      // 转派
      assignPlan() {
        const flag = this.tableData1.data.every(item => item.isCheckbox === false)
        if (flag) {
          this.$message({
            type: 'warning',
            message: '请选择要操作的行'
          })
          return
        }
        var arr = []
        this.tableData1.data.filter(item => {
          if (item.isCheckbox === true) {
            arr.push(item.csmAddressId)
          }
        })
        this.$refs.redeploy.open({
          planCode: this.temp.planCode,
          csmAddressIds: arr.join(',')
        })
      },
      // 更新数据
      redUpDataTable() {
        // 安检人员明细
        this.$refs.lbTable.fetch({ currentPage: 1 })
        // 安检客户明细
        this.$refs.lbTablePer.fetch({ currentPage: 1 })
      },
      tabsClick(val) {
        this.headerCheckbox = false
        if (val.name === 'clientInfo') {
          this.$nextTick(() => {
            this.$refs.lbTablePer.fetch({ currentPage: 1 })
          })
        }
      },
      // 全选/反选
      changeBox(val) {
        this.headerCheckbox = val
        this.tableData1.data = this.tableData1.data.map(item => {
          return { ...item, isCheckbox: val }
        })
      },
      onChangeBox(ind) {
        this.tableData1.data = this.tableData1.data.map((item, index) => {
          if (ind === index) {
            item.isCheckbox = !item.isCheckbox
          }
          return { ...item }
        })
        const flag = this.tableData1.data.every(item => item.isCheckbox === true)
        if (flag) {
          this.headerCheckbox = true
        } else {
          this.headerCheckbox = false
        }
      },
      // 选择适用机构
      selectTreeChange(value) {
        this.query.orgSNNo = value.orgSNNo
        this.personLsit()
      },
      // 查询
      search() {
        this.$refs.lbTablePer.fetch({ currentPage: 1 })
      },
      // 安检客户明细
      async fetchDataPer({ currentPage, pageSize }) {
        const params = {
          ...this._getQuery(this.query),
          planCode: this.temp.planCode,
          pageIndex: currentPage,
          pageSize
        }
        if (this.param) {
          params[this.qType] = this.param
        }
        if (!this.query.orgSNNo) {
          params.orgSNNo = ''
        }
        if (!this.query.checkUserId) {
          params.checkUserId = 0
        }
        if (!this.query.isChecked) {
          params.isChecked = -1
        }
        const res = await gasCheckPlanClientList(params)
        this.tableData1.data = res.data.rows.map(item => {
          return { ...item, isCheckbox: false }
        })
        if (currentPage === 1) this.tableData1.total = res.data.total
      },
      reset() {
        this.visible = false
        this.temp = {}
        this.date = []
        this.headerCheckbox = false
        this.activeName = 'personnelInfo'
        this.qType = 'csmPhone'
        this.param = ''
        this.personMap = []
        this.query = {
          orgSNNo: '',
          checkUserId: '',
          isChecked: ''
        }
      },
      // 安检人
      async personLsit() {
        const res = await gasCheckPlanClientMember({
          orgSNNo: this.query.orgSNNo
        })
        this.personMap = res.data
      },
      // 未安检户数/安检总户数
      notHouseholds(row, type) {
        const val = {
          checkUserId: row.operatorId,
          isChecked: type,
          planCode: row.planCode
        }
        this.$refs.households.open(val)
      },
      // 安检人员明细
      async fetchData({ currentPage, pageSize }) {
        const res = await gasCheckPlanPersonList({
          planCode: this.temp.planCode,
          pageIndex: currentPage,
          pageSize
        })
        this.tableData.data = res.data.rows
        if (currentPage === 1) this.tableData.total = res.data.total
      },
      // 清除对象空属性
      _getQuery(obj) {
        const query = {}
        for (const key in obj) {
          if (obj.hasOwnProperty(key)) {
            if (obj[key] !== '') {
              query[key] = obj[key]
            }
          }
        }
        return query
      }
    }
  }
</script>

<style lang="scss" scoped>
.item {
  margin-bottom: 30px;
  .title {
    display: flex;
    align-items: center;
    margin-bottom: 20px;
    .title-icon {
      display: inline-block;
      width: 4px;
      height: 18px;
      margin-right: 6px;
      background: #01999f;
    }
    .title-text {
      font-family: Microsoft YaHei, Microsoft YaHei-Bold;
      font-size: 14px;
      font-weight: 700;
      color: #01999f;
    }
  }
  &:last-child {
    margin-bottom: 0;
  }
  .content {
    margin-bottom: 30px;
  }
}
</style>
